package com.estate.common.utils;

import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.microsoft.graph.models.*;
import com.microsoft.graph.serviceclient.GraphServiceClient;
import com.microsoft.graph.users.item.sendmail.SendMailPostRequestBody;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class EmailService {

    @Resource
    private GraphServiceClient graphServiceClient;

    @Value("${azure.user-principal-name}")
    private String senderUserPrincipalName;


    /**
     * 发送邮件
     * @param toAddressList
     * @param subject
     * @param htmlContent
     * @return
     */
    public boolean sendHtmlEmail(List<String> toAddressList, String subject, String htmlContent) {

        GraphServiceClient graphClient = new GraphServiceClient(new ClientSecretCredentialBuilder()
                .clientId("69398eda-e8ac-45f8-94f7-920407826874")
                .clientSecret("_UX8Q~BG6-PbYPZkZfbkcGWLrPr0lWAdmZdR1ca_")
                .tenantId("f5a6ca84-4ca3-4faf-9169-74778f33516a")
                .build(), "https://graph.microsoft.com/.default");
        try {
            Message message = new Message();
            message.setSubject(subject);
            message.setIsReadReceiptRequested(true);

            // 设置邮件正文
            ItemBody body = new ItemBody();
            body.setContentType(BodyType.Html);
            body.setContent(htmlContent);
            message.setBody(body);

            // 设置收件人
            LinkedList<Recipient> toRecipients = new LinkedList<>();
            for (String toAddress : toAddressList) {
                Recipient recipient = new Recipient();
                EmailAddress emailAddress = new EmailAddress();
                emailAddress.setAddress(toAddress);
                recipient.setEmailAddress(emailAddress);
                toRecipients.add(recipient);
            }
            message.setToRecipients(toRecipients);

//            // 方式一：直接创建并发送邮件，无返回值
//            SendMailPostRequestBody mailBody = new SendMailPostRequestBody();
//            mailBody.setMessage(message);
//            mailBody.setSaveToSentItems(true);
//            graphClient.users()
//                    .byUserId(senderUserPrincipalName)
//                    .sendMail()
//                    .post(mailBody);
//            System.out.println("sendMail");


            // 方式二：创建草稿邮件之后，拿到messageId，再发送邮件
            // 1. 创建草稿邮件
            Message savedMessage = graphClient.users()
                    .byUserId("info@mcconnellbourn.com.au")
                    .messages()
                    .post(message);
            String messageId = savedMessage.getId();
            System.out.println("messages：" + messageId);

            // 2. 发送邮件
            graphClient.users()
                    .byUserId("info@mcconnellbourn.com.au")
                    .messages()
                    .byMessageId(messageId)
                    .send()
                    .post();
            System.out.println("messages send");

            // 3. 查看邮件已读状态 isRead目前一直返回的都是true
//            Message messageDetail = graphClient.users()
//                    .byUserId("info@mcconnellbourn.com.au")
//                    .messages()
//                    .byMessageId(messageId)
//                    .get();

            return true;

        } catch (Exception e) {
            System.err.println("发送邮件时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    //根据sendHtmlEmail写一个针对一个收件人发送邮件
    public boolean sendHtmlEmail(String toAddress, String subject, String htmlContent) {
        return sendHtmlEmail(List.of(toAddress), subject, htmlContent);
    }

    // test main
    public static void main(String[] args) {

        try {
            final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                    .clientId("69398eda-e8ac-45f8-94f7-920407826874")
                    .clientSecret("_UX8Q~BG6-PbYPZkZfbkcGWLrPr0lWAdmZdR1ca_")
                    .tenantId("f5a6ca84-4ca3-4faf-9169-74778f33516a")
                    .build();

            GraphServiceClient graphClient = new GraphServiceClient(clientSecretCredential, "https://graph.microsoft.com/.default");

            Message message = new Message();
            message.setSubject("这是一封测试邮件");
//            message.setIsReadReceiptRequested(true);
//            message.setIsRead(false);

            // 设置邮件正文
            ItemBody body = new ItemBody();
            body.setContentType(BodyType.Html);
            body.setContent("<p>这是一封来自 <b>Microsoft Graph Java SDK</b> 的测试邮件。</p>");
            message.setBody(body);

            // 设置收件人
            LinkedList<Recipient> toRecipients = new LinkedList<>();
            Recipient recipient = new Recipient();
            EmailAddress emailAddress = new EmailAddress();
            emailAddress.setAddress("1208771315@qq.com");
            recipient.setEmailAddress(emailAddress);
            toRecipients.add(recipient);
            message.setToRecipients(toRecipients);

            // 方式一：直接创建并发送邮件，无返回值
//            SendMailPostRequestBody mailBody = new SendMailPostRequestBody();
//            mailBody.setMessage(message);
//            mailBody.setSaveToSentItems(true);
//            graphClient.users()
//                    .byUserId("info@mcconnellbourn.com.au")
//                    .sendMail()
//                    .post(mailBody);
//            System.out.println("sendMail");


//            // 方式二：创建草稿邮件之后，拿到messageId，再发送邮件
//            // 1. 创建草稿邮件
//            Message savedMessage = graphClient.users()
//                    .byUserId("info@mcconnellbourn.com.au")
//                    .messages()
//                    .post(message);
//            String messageId = savedMessage.getId();
//            System.out.println("messages：" + messageId);
//
//            // 2. 发送邮件
//            graphClient.users()
//                    .byUserId("info@mcconnellbourn.com.au")
//                    .messages()
//                    .byMessageId(messageId)
//                    .send()
//                    .post();
//            System.out.println("messages send");
//
//            // 3. 查看邮件已读状态
//            Message messageDetail = graphClient.users()
//                    .byUserId("info@mcconnellbourn.com.au")
//                    .messages()
//                    .byMessageId(messageId)
//                    .get();
//            System.out.println(messageDetail.getIsDraft());
//            System.out.println(messageDetail.getIsRead());


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}